package com.carrot.common.core.domain;

import java.io.Serializable;

import com.carrot.common.constant.HttpStatus;
import com.carrot.common.enums.BaseMsg;
import com.carrot.common.enums.ErrorCodeEnum;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;

/**
 * 响应信息主体
 *
 * @author liuhongzhen
 */
@Builder
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 成功
     */
    public static final int SUCCESS = HttpStatus.SUCCESS;

    /**
     * 失败
     */
    public static final int FAIL = HttpStatus.ERROR;

    @Setter
    @Getter
    private int code;

    @Setter
    @Getter
    private String msg;

    @Setter
    @Getter
    private T data;

    private long timestamp;

    public static <T> R<T> ok() {
        return restResult(null, SUCCESS, "操作成功");
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, SUCCESS, "操作成功");
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, SUCCESS, msg);
    }

    public static <T> R<T> fail() {
        return restResult(null, FAIL, "操作失败");
    }

    public static <T> R<T> fail(String msg) {
        return restResult(null, FAIL, msg);
    }

    public static <T> R<T> fail(T data) {
        return restResult(data, FAIL, "操作失败");
    }

    /**
     * 获取约定好的自定义的成功信息，方便前端业务特殊处理
     * @param baseMsg 状态码信息
     * @param <T> 泛型
     * @return R<T>
     */
    public static <T> R<T> fail(BaseMsg baseMsg) {
        return fail(baseMsg);
    }

    /**
     * 获取约定好的自定义的成功信息，方便前端业务特殊处理
     * @param data 业务数据
     * @param baseMsg 状态码信息
     * @param <T> 泛型
     * @return ResultWrapper<T>
     */
    public static <T> R<T> fail(T data, BaseMsg baseMsg) {
        return R.<T>builder()
                .code(baseMsg.getCode())
                .msg(baseMsg.getMessage())
                .data(data)
                .timestamp(System.currentTimeMillis())
                .build();
    }

    public static <T> R<T> fail(T data, String msg) {
        return restResult(data, FAIL, msg);
    }

    public static <T> R<T> fail(int code, String msg) {
        return restResult(null, code, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        return R.<T>builder()
                .code(code)
                .msg(msg)
                .data(data)
                .timestamp(System.currentTimeMillis())
                .build();
    }

    public static <T> Boolean isError(R<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(R<T> ret) {
        return R.SUCCESS == ret.getCode();
    }
}
